from pdf2docx import Converter
import os
from ..common.printPro import printPro
import subprocess

FILE1 = "Saas行业研究报告.pdf"
FILE2 = "360终端安全检测报告.pdf"
FILE3 = "艾瑞咨询-人工智能行业报告.pdf"
FILE4= '腾讯监控.pdf'


def convert_pdf_to_docx(pdf_file, docx_file):
    """将PDF文件转换为DOCX文件"""
    # 创建转换器实例
    cv = Converter(pdf_file)
    settings = cv.default_settings
    settings.update(
        {"float_image_ignorable_gap": 20, "parse_stream_table": True, "debug": True}
    )
    try:
        # 执行转换操作，返回转换的总页数
        cv.convert(docx_file, start=5, end=7, **settings)
        print(f"PDF文件 '{pdf_file}' 已成功转换为DOCX文件 '{docx_file}'")
        return True
    except Exception as e:
        print(f"转换过程中出现错误: {str(e)}")
        return False
    finally:
        # 确保关闭转换器
        cv.close()


def open_file(file_path):
    """在Mac系统上打开文件"""
    try:
        subprocess.call(("open", file_path))
        print(f"已自动打开文件: {file_path}")
    except Exception as e:
        print(f"无法打开文件: {str(e)}")


if __name__ == "__main__":
    # 获取当前脚本所在的目录
    current_dir = os.path.dirname(os.path.abspath(__file__))

    # 定义输入的PDF文件和输出的DOCX文件路径
    pdf_filename = FILE1
    pdf_path = os.path.join(current_dir, pdf_filename)
    docx_path = os.path.join(current_dir, "output.docx")

    # 执行转换
    conversion_success = convert_pdf_to_docx(pdf_path, docx_path)

    # 如果转换成功，自动打开DOCX文件
    if conversion_success and os.path.exists(docx_path):
        open_file(docx_path)
